<?php

namespace common\base;

use Yii;
use yii\db\Exception;

/**
 * Model is the base class for data models.
 *
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class Model extends \yii\base\Model {

    use \common\traits\ModelErrors;
    use \common\traits\DataPierces;

    const TRANS_FUNC_PREFIX = 'transact';

    /**
     * AR事务封装
     *
     * @param $method
     * @param null $error
     * @return mixed|void
     * @throws ModelHttpException
     */
    public function executeTransaction($method, $error = null) {
        $transaction = Yii::$app->db->beginTransaction();
        try {
            $executeResult = call_user_func(array($this, self::TRANS_FUNC_PREFIX . ucfirst($method)));
            $transaction->commit();
        } catch (Exception $e) {
            $transaction->rollBack();
            if ($error !== null) {
                return $error;
            }
            $msg = $e->getMessage();
            if (YII_DEBUG) {
                Yii::error($e->errorInfo);
            }
            return $this->saveError($msg, false);
        }
        return $executeResult;
    }

    /**
     * 分离增删交叉数据集
     * @param array $old 原始数据
     * @param array $now 当前数据
     * @return array
     */
    public function divideViaData($old, $now) {
        $intersect = array_intersect($old, $now);
        $remove = array_diff($old, $intersect);
        $create = array_diff($now, $intersect);
        return compact('remove', 'create');
    }

    /**
     * Populates the model with input data.
     */
    public function getCommonCache() {
        if (Yii::$app->has('commonCache')) {
            return Yii::$app->commonCache;
        }
        return Yii::$app->cache;
    }

}
